import {
	SerializedError,
	createAsyncThunk,
	createSlice,
} from '@reduxjs/toolkit'
import { RootState, TCatalogData } from '../../types'
import api from '../../../api'
import { TAllProductsResponse } from '../../../api/api'

type TAllProductsState = {
	data: TCatalogData[] | null
	loading: boolean
	error: SerializedError | null | unknown
}

const initialState: TAllProductsState = {
	data: null,
	loading: false,
	error: null,
}

const sliceName = 'allProducts'

export const fetchAllProducts = createAsyncThunk<TAllProductsResponse, void>(
	`${sliceName}/fetchAllProducts`,
	async (_, { getState }) => {
		try {
			const response = await api(
				(getState() as RootState).user.token
			).getAllProducts()
			return response
		} catch (error) {
			return error
		}
	}
)

export const allProductsSlice = createSlice({
	name: sliceName,
	initialState,
	reducers: {
		resetAllProducts: (state) => {
			state.data = null
		},
	},
	extraReducers: (builder) => {
		builder
			.addCase(fetchAllProducts.fulfilled, (state, action) => {
				state.data = action.payload.products
				state.loading = false
			})
			.addCase(fetchAllProducts.pending, (state) => {
				state.loading = true
				state.error = null
			})
			.addCase(fetchAllProducts.rejected, (state, action) => {
				state.error = action.payload
				state.loading = false
			})
	},
})
